package com.ede.roverhu.simplebackstage.Activities;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;


import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;

import android.os.Bundle;

import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;

import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.ede.roverhu.simplebackstage.Constant.HandlerConstant;
import com.ede.roverhu.simplebackstage.Domain.QueryClassDomain;
import com.ede.roverhu.simplebackstage.Domain.schoolClassBase;
import com.ede.roverhu.simplebackstage.Domain.timeTableClassInfoDomain;
import com.ede.roverhu.simplebackstage.Engine.htmlHander;
import com.ede.roverhu.simplebackstage.Http.HttpClient;
import com.ede.roverhu.simplebackstage.R;

import com.ede.roverhu.simplebackstage.Utils.ToastUtils;

import java.util.ArrayList;

public class TimetableActivity extends BaseActivity {
    private String a = "";
    private TextView mtextview;
    private Spinner mspinner;
    private SwipeRefreshLayout refreshlayout;
    private ListView mlistview;
    private CourseAdapter courseAdapter;
    private Button mButton;
    private ArrayList<schoolClassBase> clist;
    private int page = 1;
    private ArrayList<timeTableClassInfoDomain> courselist;
    private QueryClassDomain queryClassDomain;
    private QueryClassDomain mainClassDoamin;

    private int year, month, day;
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String str = msg.obj.toString();
            switch (msg.what) {
                case HandlerConstant.QUERYCLASSTIMETABLE_SUCCESS:
                    if (clist==null) {
                        clist = htmlHander.getTimetableClass(getApplicationContext(), str);
                        String[] cArr = new String[clist.size()];
                        for (int z = 0; z < clist.size(); z++) {
                            cArr[z] = clist.get(z).className;
                        }
                        mspinner.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, cArr));
                        mspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                if (!clist.get(i).classId.equals("0"))
                                    queryClassDomain.cid = clist.get(i).classId;
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                    }
                    courselist = htmlHander.getTimetableInfoList(getApplicationContext(), str);
                    if (courselist.isEmpty()||courselist.size()==0)
                        ToastUtils.show(TimetableActivity.this,"当天无课程数据");
                    courseAdapter = new CourseAdapter(getApplicationContext(), courselist);
                    mlistview.setAdapter(courseAdapter);

                    refreshlayout.setRefreshing(false);
                    break;
                case HandlerConstant.QUERYCLASSTIMETABLE_SUCCESS4PM:
                    break;
                case HandlerConstant.QUERYCLASSTIMETABLE_FAIL:
                    ToastUtils.show(TimetableActivity.this, "查询失败");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timetable);

        Intent intent = getIntent();
        a = intent.getStringExtra("iD");
        String title = intent.getStringExtra("title");
        ActionBar actionBar = getSupportActionBar();
        actionBar.setSubtitle(title);
        actionBar.setDefaultDisplayHomeAsUpEnabled(true);
        getdate();
        init();
    }

    private void getdate() {
        java.util.Calendar Cal = java.util.Calendar.getInstance();
        year = Cal.get(java.util.Calendar.YEAR);
        month = Cal.get(java.util.Calendar.MONTH);
        day = Cal.get(java.util.Calendar.DAY_OF_MONTH);
    }

    private void init() {
        mButton = (Button) findViewById(R.id.submit);
        mtextview = (TextView) findViewById(R.id.timepicker);
        mtextview.setText(year + "-" + (++month) + "-" + day);
        mspinner = (Spinner) findViewById(R.id.class_sp);
        refreshlayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mlistview = (ListView) findViewById(R.id.listview);

        getdate();
        mtextview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        mtextview.setText(i + "-" + (++i1) + "-" + i2);
                    }
                };
                DatePickerDialog dialog = new DatePickerDialog(TimetableActivity.this, 0, listener, year, month, day);
                dialog.show();
            }
        });
        queryClassDomain = new QueryClassDomain();
        mainClassDoamin = new QueryClassDomain();
        queryClassDomain.id = a;
        //queryClassDomain.time=mtextview.getText().toString();
        HttpClient.queryTimetable4Class(queryClassDomain, 1, mhandler);

        refreshlayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        refreshlayout.setDistanceToTriggerSync(400);
        refreshlayout.setSize(SwipeRefreshLayout.DEFAULT);
        // swipeRefreshLayout.setRefreshing(false);
        refreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                HttpClient.queryTimetable4Class(mainClassDoamin, 1, mhandler);
            }
        });

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HttpClient.queryTimetable4Class(queryClassDomain, 1, mhandler);
                queryClassDomain.time=mtextview.getText().toString();
                mainClassDoamin = queryClassDomain;

            }
        });

        mlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(TimetableActivity.this,CourseInfoActivity.class);
                intent.putExtra("iD",courselist.get(i).iD);
                startActivity(intent);
            }
        });
    }


    public class CourseAdapter extends BaseAdapter {
        private ArrayList<timeTableClassInfoDomain> list;
        private Context context;

        public CourseAdapter(Context context, ArrayList<timeTableClassInfoDomain> list) {
            this.context = context;
            this.list = list;
//            LogUtils.e("已创建");
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return Long.parseLong(list.get(i).iD);
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
//            LogUtils.e("已生成");
            View v;
            Viewholder viewholder;
            if (view != null && view instanceof RelativeLayout) {
                v = view;
                viewholder = (Viewholder) v.getTag();
            } else {
                v = View.inflate(context, R.layout.item_courseinfo, null);
                viewholder = new Viewholder();
                viewholder.courseName = (TextView) v.findViewById(R.id.item_courseinfo_coursename_tv);
                viewholder.classNum = (TextView) v.findViewById(R.id.item_courseinfo_classNum_tv);
                viewholder.place = (TextView) v.findViewById(R.id.item_courseinfo_place_tv);
                viewholder.time = (TextView) v.findViewById(R.id.item_courseinfo_time_tv);
                v.setTag(viewholder);
            }

            viewholder.courseName.setText(list.get(i).courseName);
            viewholder.classNum.setText(list.get(i).classNum);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                viewholder.place.setText(Html.fromHtml(list.get(i).place, Html.FROM_HTML_MODE_LEGACY));
            } else {
                viewholder.place.setText(Html.fromHtml(list.get(i).place));
            }
            viewholder.time.setText(list.get(i).time);
            return v;
        }

        public void addlist(ArrayList<timeTableClassInfoDomain> list) {
            this.list.addAll(list);
        }
    }

    static class Viewholder {
        TextView courseName;
        TextView classNum;
        TextView place;
        TextView time;
    }

}
